﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Practices.Unity;

namespace Framework.Modules
{
	public static class ModulesInitializer
	{
		private static readonly object Sync = new object();
		private static bool initialized;

		public static void Initialize(IUnityContainer container)
		{
			lock (Sync)
			{
				if (initialized)
				{
					return;
				}

				initialized = true;
			}

			string path = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
			var catalog = new DirectoryCatalog(path);
			var mefcontainer = new CompositionContainer(catalog);
			modules = mefcontainer.GetExportedValues<IModule>(); ;

			foreach (IModule module in modules)
			{
				module.Container = container;
				module.Initialize();
			}
		}

		public static IEnumerable<IModule> modules;
	}
}